package com.rmb.aop;

import com.rmb.annotation.SystemLog;
import com.rmb.entity.OperationLog;
import com.rmb.service.OperationLogService;
import com.rmb.utils.IpInfoUtil;
import com.rmb.utils.ObjectUtil;
import com.rmb.utils.ThreadPoolUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.NamedThreadLocal;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author ZhaoMuYang
 */
@Aspect
@Component
@Slf4j
public class SystemLogAspect {

    private static final ThreadLocal<Date> BEGIN_TIME_THREAD_LOCAL = new NamedThreadLocal<Date>("ThreadLocal beginTime");


    @Autowired
    private OperationLogService operationLogService;


    @Autowired
    private IpInfoUtil ipInfoUtil;

    @Autowired(required = false)
    private HttpServletRequest request;

    /**
     * Controller层切点
     */
    @Pointcut("@annotation(com.rmb.annotation.SystemLog)")
    public void controllerAspect() {

    }

    /**
     * 记录操作开始时间
     * @param joinPoint
     * @throws InterruptedException
     */
    @Before("controllerAspect()")
    public void doBefore(JoinPoint joinPoint) throws InterruptedException {
        //线程绑定变量
        Date beginTime = new Date();
        BEGIN_TIME_THREAD_LOCAL.set(beginTime);
    }

    /**
     * 拦截无异常的操作
     * @param joinPoint
     */
    @AfterReturning("controllerAspect()")
    public void after(JoinPoint joinPoint) {
        try {
            String description = getControllerMethodInfo(joinPoint).get("description").toString();
            Map<String, String[]> requestParams = request.getParameterMap();

            OperationLog log = new OperationLog();

            log.setId(UUID.randomUUID().toString());
            log.setName(description);
            log.setLogType((int) getControllerMethodInfo(joinPoint).get("type"));
            log.setRequestUrl(request.getRequestURI());
            log.setRequestType(request.getMethod());
            log.setRequestParam(ObjectUtil.mapToString(requestParams));
            log.setIp(ipInfoUtil.getIpAddr(request));
            log.setCreateBy("system");
            log.setUpdateBy("system");
            log.setCreateTime(new Date());
            log.setUpdateTime(new Date());
            //请求开始时间
            long beginTime = BEGIN_TIME_THREAD_LOCAL.get().getTime();
            long endTime = System.currentTimeMillis();
            //请求耗时
            Long logElapsedTime = endTime - beginTime;
            log.setCostTime(logElapsedTime.intValue());

            //持久化
            ThreadPoolUtil.getPool().execute(new SaveSystemLogThread(log, operationLogService));

            BEGIN_TIME_THREAD_LOCAL.remove();
        } catch (Exception e) {
            log.error("AOP后置通知异常", e);
        }
    }


    /**
     * 保存日志至数据库
     */
    private static class SaveSystemLogThread implements Runnable {

        private OperationLog log;
        private OperationLogService operationLogService;

        public SaveSystemLogThread(OperationLog esLog, OperationLogService operationLogService) {
            this.log = esLog;
            this.operationLogService = operationLogService;
        }

        @Override
        public void run() {
            operationLogService.insert(log);
        }
    }

    /**
     * 获取注解中对方法的描述信息
     * @param joinPoint
     * @return
     * @throws Exception
     */
    public static Map<String, Object> getControllerMethodInfo(JoinPoint joinPoint) throws Exception {

        Map<String, Object> map = new HashMap<String, Object>(16);

        String targetName = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        Object[] arguments = joinPoint.getArgs();
        Class targetClass = Class.forName(targetName);
        Method[] methods = targetClass.getMethods();

        String description = "";
        Integer type = null;

        for (Method method : methods) {
            if (!method.getName().equals(methodName)) {
                continue;
            }
            Class[] clazzs = method.getParameterTypes();
            if (clazzs.length != arguments.length) {
                //比较方法中参数个数与从切点中获取的参数个数是否相同
                continue;
            }
            description = method.getAnnotation(SystemLog.class).description();
            type = method.getAnnotation(SystemLog.class).type().getValue();
            map.put("description", description);
            map.put("type", type);
        }
        return map;
    }

}
